import $http from '../../axios';
import {MessageBox} from 'mint-ui'; 
export default {
    namespaced: true,
    state:{
        currentUser:{
            UserToken:'',
            RefreshToken:'',
            addressInfo:'',
            userData: ''
        },
        cartNum:'',
        messageNum:'',
        reg: {
            passwordPattern: "/^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![,\\.#%'\\+\\*\\-:;^_`]+$)[,\\.#%'\\+\\*\\-:;^_`0-9A-Za-z]{8,20}$/", //8~20位,数字、英文、符号至少两种组合的字符
            phoneNumberPattern: "/^1(3|4|5|7|8)\\d{9}$/", //手机号格式
            userNamePattern: "/^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/", //6至20位，以字母开头，字母、数字、减号、下划线
            telPattern: "/^(\\(\\d{3,4}\\)|\\d{3,4}-|\\s)?\\d{7,14}$/",//固话格式
        },
        order: {
            list:'',
            addressInfo:'',
            amount: '',
            freight: '',
            invoice: '',
            voucher: '',
        },
        orderTotal: ''
    },
    mutations:{
        setUser(state,{user_name,user_token,refresh_token}){
            // 在这里把token保存起来
            state.currentUser.UserToken = user_token;
            state.currentUser.RefreshToken = refresh_token;
        },
        clearUser(state){
            state.currentUser = {
                UserToken:'',
                RefreshToken:'',
                addressInfo:'',
                userData: ''

            };
            state.cartNum = '';
            state.messageNum ='';
        },
        updateUserData(state,data){
            state.currentUser.userData = data;
        },
        updateAddressInfo(state,data){
            state.currentUser.addressInfo = data;
        },
        updateOrderList(state,data){
            state.order.list = data;
            if(data.length){
                let amount = 0;
                data.forEach(item => {
                    amount += parseInt(item.totalPrice);
                });
                state.order.amount = amount;
                state.order.freight = 0;
            }
        },
        updateOrderAddress(state,data){
            let addressInfo = state.currentUser.addressInfo;
            if(Array.isArray(addressInfo) && addressInfo.length){
                let defaultAddress = addressInfo.find(item=>{return item.isDefault});
                data = data || (defaultAddress ? defaultAddress : addressInfo[0]);
                state.order.addressInfo = data;
            }
        },
        clearOrder(state){
            state.order = {
                list:'',
                addressInfo:'',
                amount: '',
                freight: '',
                invoice: '',
                voucher: '',
            };
        },
        updateOrderTotal(state,data = ''){
            state.orderTotal = data;
        },
        deleteOneFromOrderTotal(state,id){
            let index = state.orderTotal.findIndex(item=>{
                return item.id == id;
            });
            if(index >= 0){
                state.orderTotal.splice(index,1);
            }
        },
        updateCartNum(state,num){
            state.cartNum = num;
        }
    },
    actions:{
        userLogin(context,{user_name,user_password,router,path}){
            $http.post('/oauth/token',null,{
                params: {
                    "username": user_name,
                    "password": user_password,
                    "grant_type": "password",
                    "scope": "all"
                },
                auth: {
                    username: 'client',
                    password: 'secret'
                },
                withCredentials: true
            }).then(res => {
                context.commit('setUser',{'user_name': user_name,'user_token':res.data.access_token,'refresh_token':res.data.refresh_token});
                context.commit('setSignTrue',null,{root: true});
                context.dispatch('getUserData');//获取user
                context.dispatch('getAddressInfo');//获取address
                context.dispatch('getOrderTotal');//获取订单信息
                context.dispatch('getCartNum');
                if(path) router.push(decodeURIComponent(path));
                else router.push('/');
            }).catch(error => {
                // todo登陆失败
                MessageBox.alert('登录错误，请重新输入！');
                context.commit('setSignFalse',null,{ root: true});
            })
        },
        userLogout(context,{router}){
            $http.post('public/logout',null,{showLoading:false});
            router.push({ path: '/login' });
            location.reload();
            context.commit('clearUser');
            context.commit('clearOrder');
            context.commit('updateOrderTotal');
            context.commit('setSignFalse',null,{ root: true});
        },
        getUserData(context){
            $http.get('/public/user').then(res=>{
                context.commit('updateUserData',res.data);
            })
        },
        getAddressInfo(context){
            $http.post('/address/selectByUid').then(res => {
                if(res.data.status == 1){
                    context.commit('updateAddressInfo',res.data.data);
                }
            })
        },
        getOrderTotal(context){
            $http.get('/order/selectOrder').then(res=>{
                if(res.data.status == 1) {
                    let temp = res.data.data.map(item=>{
                        item.allShow = false;
                        item.notPaidShow = false;
                        item.notReceivedShow = false;
                        item.finishedShow = false;
                        return item;
                    });
                    context.commit('updateOrderTotal',temp);
                }

            })
        },
        getCartNum(context){
            $http.post('/shoppingcar/count',null,{showLoading:false}).then(res=>{
                if(res.data.status == 1){
                    context.commit('updateCartNum',parseInt(res.data.totalCount));
                }
            })
        }
    }
}